import { getUser, IUser, setRoutes, setUser } from '@/service/user'
import store from '@/store'
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import { PermissionModule } from './permission'

export interface IUserState {
    user: IUser
}

@Module({
    dynamic: true,
    store,
    name: 'user'
})
class User extends VuexModule implements IUserState {
    user: IUser = {
        name: '',
        routes: []
    }

    // @Mutation
    // private SET_ROUTES(routes: string[]) {
    //     this.routes = routes
    // }

    @Mutation
    private SET_USER(user: IUser) {
        this.user = user
    }

    @Mutation
    private RESET_USER() {
        this.user = {
            name: '',
            routes: []
        }
    }

    // @Action
    // public SetRoutes(routes: string[]) {
    //     this.SET_ROUTES(routes)
    //     // 保存一份在本地
    //     setRoutes(routes)
    // }

    @Action
    public UpdateUser(user?: IUser) {
        if (!user) {
            user = getUser()
        }
        this.SET_USER(user)
        // 保存一份在本地
        setUser(user)
        PermissionModule.GenerateRoutes(user.routes)
    }

    @Action
    public ResetUser() {
        this.RESET_USER()
        setUser(this.user)
    }
}

export const UserModule = getModule(User)
